package com.example.demo.exception;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    public String arithmeticExceptionHandler(ArithmeticException ex) {
        System.out.println("ArithmeticException======Check your code.");
        return "ArithmeticException======Check your code.";
    }
    @ExceptionHandler(WebExchangeBindException.class)
    public String methodArgumentNotValidException(WebExchangeBindException ex) {
        BindingResult bindingResult = (ex).getBindingResult();
        List<FieldError> allErrors = bindingResult.getFieldErrors();
        StringBuilder builder = new StringBuilder();
        for (FieldError fieldError : allErrors) {
            builder.append(",")
                    .append(fieldError.getField())
                    .append(":")
                    .append(fieldError.getDefaultMessage());
        }
        System.out.println("ArithmeticException======Check your code.");
        return builder.deleteCharAt(0).toString();
    }
//    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
//    public String methodNotSupportExceptionHandler(HttpRequestMethodNotSupportedException ex) {
//        System.out.println("==============Method not support==========Check your url method");
//        return "==============Method not support==========Check your url method";
//    }
//
//    //处理自定义异常
//    @ExceptionHandler(MyException.class)
//    public String myExceptionHandler(MyException ex) {
//        System.out.println("=============my exception occur");
//        return "=====================MyException Occur===========";
//    }

}